import os
import subprocess

from docx import Document
from Data import search_file


# 维护与诊断目录编号
def diagnosis_or_maintenance(flag, is_only_dir, filepaths):
    sysop_flag = False
    cref_flag = None
    root_path = None
    if is_only_dir is None:
        return filepaths

    if filepaths == "-1":
        return "-1"
    content = []
    updated_paths = filepaths
    count = 0
    for path in filepaths:
        if "维护命令" in path.split('\\')[-3]:
            if count == 0:
                root_path = path.rsplit("维护命令", 1)[0]
            count = count + 1
            cref_flag = "维护命令"
        if "诊断命令" in path.split('\\')[-3]:
            if count == 0:
                root_path = path.rsplit("诊断命令", 1)[0]
            count = count + 1
            cref_flag = "诊断命令"

    scg_path = f'{root_path}维护命令'
    cref_path = f'{root_path}诊断命令'
    scg_flyleaf_path = f'{scg_path}\\封面和扉页'
    cref_flyleaf_path = f'{cref_path}\\封面和扉页'
    # print(flyleaf_path)

    # 检查封面和扉页文件夹是否存在
    if cref_flag == "维护命令":
        if not os.path.exists(scg_flyleaf_path):
            print(f"\033[91m错误：找不到封面和扉页文件夹:\033[0m {scg_flyleaf_path}")
            # print("请检查维护命令与诊断命令编号")
            print("程序执行完成!!!")
            sysop_flag = True
            return "-1"

        # 遍历封面和扉页文件夹
        try:
            for file in os.listdir(scg_flyleaf_path):
                if file.endswith('.docx'):
                    if "00-pdf" in file:
                        if "扉页" in file:
                            flyleaf = f'{scg_flyleaf_path}\\{file}'

                            # 读取文档内容
                            doc = Document(flyleaf)
                            manual_found = False
                            # content = []

                            # 遍历段落查找"手册"之后的内容
                            for para in doc.paragraphs:
                                if "以下手册" in para.text:
                                    manual_found = True
                                    continue
                                if manual_found and para.text.strip():
                                    # 添加序号，从01开始
                                    index = len(content) + 1
                                    formatted_text = f"{index:02d}-{para.text.strip()}"
                                    content.append(formatted_text)
                            # print(content)
                            break

            # 遍历配置指南目录
            scg_folders = []
            if os.path.exists(scg_path):
                for folder in os.listdir(scg_path):
                    folder_path = os.path.join(scg_path, folder)
                    if os.path.isdir(folder_path) and folder != "00-pdf" and folder != "封面和扉页":
                        scg_folders.append(folder)
                # print(scg_folders)

                # 后续的检查和重命名逻辑保持不变
                for name in content:
                    match_found = False
                    for folder in scg_folders:
                        if name.split('-')[1] in folder:
                            match_found = True
                    if not match_found:
                        print(f"\033[93m警告：维护命令分册 {name} 缺失\033[0m")
                        sysop_flag = True
                for folder in scg_folders:
                    found_match = False
                    for name in content:
                        if "-" in folder:
                            if folder.split('-')[1] in name:
                                found_match = True
                                if folder.split('-')[0] == name.split('-')[0]:
                                    continue
                                else:
                                    try:
                                        old_path = os.path.join(scg_path, folder)
                                        new_path = os.path.join(scg_path, name)
                                        if flag:
                                            # 使用 SVN 命令重命名
                                            subprocess.run(['svn', 'mv', old_path, new_path], check=True)
                                        else:
                                            os.rename(old_path, new_path)
                                        print(f"重命名维护命令分册: {folder} -> {name}")
                                        for i, updated_path in enumerate(updated_paths):
                                            if old_path in updated_path:
                                                updated_paths[i] = updated_path.replace(old_path, new_path)
                                    except Exception as e:
                                        print(f"\033[91m重命名维护命令分册失败:\033[0m {str(e)}")
                                        sysop_flag = True
                        else:
                            if folder in name:
                                found_match = True
                                try:
                                    old_path = os.path.join(scg_path, folder)
                                    new_path = os.path.join(scg_path, name)
                                    if flag:
                                        # 使用 SVN 命令重命名
                                        subprocess.run(['svn', 'mv', old_path, new_path], check=True)
                                    else:
                                        os.rename(old_path, new_path)
                                    print(f"重命名维护命令分册: {folder} -> {name}")
                                    for i, updated_path in enumerate(updated_paths):
                                        if old_path in updated_path:
                                            updated_paths[i] = updated_path.replace(old_path, new_path)
                                except Exception as e:
                                    print(f"\033[91m重命名维护命令分册失败:\033[0m {str(e)}")
                                    sysop_flag = True
                    if not found_match:
                        print(f"\033[93m警告：扉页中未找到维护命令分册 {folder}\033[0m ")
                        sysop_flag = True
            else:
                print(f"\033[91m错误：找不到维护命令目录:\033[0m {scg_path}")
                sysop_flag = True

        except Exception as e:
            print(f"\033[91m处理文件出错:\033[0m {str(e)}")
            print(f"\033[91m遍历文件夹出错:\033[0m {str(e)}")
            sysop_flag = True

    if cref_flag == "诊断命令":
        if not os.path.exists(cref_flyleaf_path):
            print(f"\033[91m错误：找不到封面和扉页文件夹:\033[0m {cref_flyleaf_path}")
            # print("请检查维护命令与诊断命令编号")
            print("程序执行完成!!!")
            sysop_flag = True
            return "-1"

        # 遍历封面和扉页文件夹
        try:
            for file in os.listdir(cref_flyleaf_path):
                # print(file)
                if file.endswith('.docx'):
                    if "扉页" in file:
                        # print(file)
                        flyleaf = f'{cref_flyleaf_path}\\{file}'

                        # 读取文档内容
                        doc = Document(flyleaf)
                        manual_found = False
                        # content = []

                        # 遍历段落查找"手册"之后的内容
                        for para in doc.paragraphs:
                            if "以下手册" in para.text:
                                manual_found = True
                                continue
                            if manual_found and para.text.strip():
                                # 添加序号，从01开始
                                index = len(content) + 1
                                formatted_text = f"{index:02d}-{para.text.strip()}"
                                content.append(formatted_text)
                        # print(content)
                        break

            # 遍历命令参考目录
            scg_folders = []
            if os.path.exists(cref_path):
                for folder in os.listdir(cref_path):
                    folder_path = os.path.join(cref_path, folder)
                    if os.path.isdir(folder_path) and folder != "00-pdf" and folder != "封面和扉页":
                        scg_folders.append(folder)
                # print(scg_folders)

                for name in content:
                    match_found = False
                    for folder in scg_folders:
                        if name.split('-')[1] in folder:
                            match_found = True
                    if not match_found:
                        print(f"\033[93m警告：诊断命令分册 {name} 缺失\033[0m")
                        sysop_flag = True
                for folder in scg_folders:
                    found_match = False
                    for name in content:
                        if "-" in folder:
                            if folder.split('-')[1] in name:
                                found_match = True
                                if folder.split('-')[0] == name.split('-')[0]:
                                    continue
                                else:
                                    try:
                                        old_path = os.path.join(cref_path, folder)
                                        new_path = os.path.join(cref_path, name)
                                        if flag:
                                            # 使用 SVN 命令重命名
                                            subprocess.run(['svn', 'mv', old_path, new_path], check=True)
                                        else:
                                            # print(f'{old_path}---》{new_path}')
                                            os.rename(old_path, new_path)
                                        print(f"重命名诊断命令分册: {folder} -> {name}")
                                        for i, updated_path in enumerate(updated_paths):
                                            if old_path in updated_path:
                                                updated_paths[i] = updated_path.replace(old_path, new_path)
                                    except Exception as e:
                                        print(f"\033[91m重命名诊断命令文件夹失败:\033[0m {str(e)}")
                                        sysop_flag = True
                        else:
                            if folder in name:
                                found_match = True
                                try:
                                    old_path = os.path.join(cref_path, folder)
                                    new_path = os.path.join(cref_path, name)
                                    if flag:
                                        # 使用 SVN 命令重命名
                                        subprocess.run(['svn', 'mv', old_path, new_path], check=True)
                                    else:
                                        # print(f'{old_path}---》{new_path}')
                                        os.rename(old_path, new_path)
                                    print(f"重命名诊断命令分册: {folder} -> {name}")
                                    for i, updated_path in enumerate(updated_paths):
                                        if old_path in updated_path:
                                            updated_paths[i] = updated_path.replace(old_path, new_path)
                                except Exception as e:
                                    print(f"\033[91m重命名诊断命令文件夹失败:\033[0m {str(e)}")
                                    sysop_flag = True
                    if not found_match:
                        print(f"\033[93m警告：扉页中未找到诊断命令分册 {folder}\033[0m ")
                        sysop_flag = True
            else:
                print(f"\033[91m错误：找不到诊断命令目录:\033[0m {cref_path}")
                sysop_flag = True

        except Exception as e:
            print(f"\033[91m处理文件出错:\033[0m {str(e)}")
            print(f"\033[91m遍历文件夹出错:\033[0m {str(e)}")
            sysop_flag = True

    if is_only_dir:
        print("程序执行完成!!!")
        return "-1"
    else:
        print("*" * 50)
        return updated_paths, sysop_flag


if __name__ == '__main__':
    diagnosis_or_maintenance(True, True)
